package de.tc.stammdatenverwaltung.gui;

import de.tc.stammdatenverwaltung.functions.ExtensionFileFilter;
import de.tc.stammdatenverwaltung.functions.commonFunctions;
import java.awt.Color;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

public class exportDialog extends javax.swing.JDialog {

    /** Creates new form exportDialog */
    public exportDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jLabel3 = new javax.swing.JLabel();
    jTextField2 = new javax.swing.JTextField();
    jCheckBox1 = new javax.swing.JCheckBox();
    jButton2 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

    jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

    jLabel1.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
    jLabel1.setText("Export von Kontakten ...");

    jLabel2.setText("Pfad und Dateiname angeben:");

    jTextField1.setText("...");

    jButton1.setText("Datei wählen");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton1ActionPerformed(evt);
      }
    });

    jLabel3.setText("Spaltentrenner (einzelnes Zeichen!)");

    jTextField2.setText(";");

    jCheckBox1.setText("Spaltenköpfe hinzufügen");

    jButton2.setText("Export beginnen");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton2ActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel1Layout.createSequentialGroup()
        .addComponent(jLabel1)
        .addGap(294, 294, 294))
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
          .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 482, Short.MAX_VALUE)
          .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton1))
          .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jCheckBox1)
              .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addGap(116, 116, 116)))
        .addGap(22, 22, 22))
    );
    jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel1Layout.createSequentialGroup()
        .addComponent(jLabel1)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jLabel2)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jButton1))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel3)
          .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jCheckBox1)
        .addGap(18, 18, 18)
        .addComponent(jButton2)
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addContainerGap())
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton1ActionPerformed
    {//GEN-HEADEREND:event_jButton1ActionPerformed
      String home = System.getProperty("user.home");
      JFileChooser jf1 = new JFileChooser(new File(home));
      FileFilter ff1 = new ExtensionFileFilter("CSV", "csv");
      jf1.setFileFilter(ff1);
      jf1.setMultiSelectionEnabled(false);
      if (jf1.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
      { //Datei ausgewaehlt
        jTextField1.setText(jf1.getSelectedFile().getAbsolutePath());
      }
}//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton2ActionPerformed
    {//GEN-HEADEREND:event_jButton2ActionPerformed
      Color old = jButton2.getBackground();
      jButton2.setBackground(Color.red);
      startExport();
      jButton2.setBackground(old);
}//GEN-LAST:event_jButton2ActionPerformed

    private void startExport()
    {
      File f = null;
      if ( jTextField1.getText().contains(".CSV") || jTextField1.getText().contains(".csv") )
        f = new File( jTextField1.getText() );
      else
        f = new File( jTextField1.getText() + ".CSV" );
      
      String separator = jTextField2.getText().trim();
      boolean weiter = true;

      if (f.exists() && f.isDirectory())
      {
        JOptionPane.showMessageDialog(this, "Der angegebene Ort ist ein Verzeichnis, " +
                "Verzeichnisse können nicht überschrieben werden.\r\n" +
                "Bitte gib einen Dateinamen an.", "Fehler", JOptionPane.ERROR_MESSAGE);
        weiter = false;
      }
      else if (f.exists() && f.isFile())
      {
        if (JOptionPane.showConfirmDialog(null, "Soll die ausgeählte Datei wirklich überschrieben werden?",
              "Sicherheitsfrage:", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
          weiter = false;
      }

      try
      {
        if (weiter)
        {
          //erst lesen versuchen, dann Datei anlegen, sonst haben wir am ende umsonst das FS vollgeknallt
          Statement stmt = Main.con.createStatement();
          ResultSet rs1 = stmt.executeQuery("select * from stammdaten");

          if ( !f.exists() )
            f.createNewFile();


          FileWriter fw = new FileWriter(f);
          BufferedWriter bw = new BufferedWriter(fw);

          String zeile = "";
          String kopf = "";

          ResultSetMetaData rsmd = rs1.getMetaData();

          if (jCheckBox1.isSelected())
          {
            for (int i = 1; i <= rsmd.getColumnCount(); i++)
              kopf = kopf.concat(rsmd.getColumnName(i) + separator);

            kopf = kopf.substring(0, kopf.length() - 1); //letzter Separator weg

            bw.write(kopf);
            bw.newLine();
            bw.flush();
          }
          String value = null;
          while (rs1.next()) //ALLES durchgehen und in datei pumpen
          {
            zeile = "";
            for (int i = 1; i <= rsmd.getColumnCount(); i++)
            {
              value = rs1.getString(i);
              if ( (value != null) && !(value.equals("null")) ) //sonst gibts beim nächsten import probleme
                zeile = zeile.concat( value.concat(separator) );
              else
                zeile = zeile.concat( "" + separator);
            }
            //zeile = zeile.substring(0, zeile.length() - 2); //letzter Separator weg
            bw.write(zeile);
            bw.newLine();
            bw.flush();
          }

          bw.flush();
          bw.close();
          fw.close();
          rsmd = null;
          rs1.close();
          stmt.close();

          JOptionPane.showMessageDialog(this, "Die Kontakte wurden erfolgreich exportiert.",
                "Information", JOptionPane.INFORMATION_MESSAGE);
        }
      }
      catch (SQLException sqle)
      {
        JOptionPane.showMessageDialog(this, "Es konnten keine Daten aus der Datenbank abgerufen werden.\r\n" +
          sqle.getLocalizedMessage(), "Fehler", JOptionPane.ERROR_MESSAGE);
        sqle.printStackTrace();
      }
      catch (IOException ioe)
      {
        JOptionPane.showMessageDialog(this, "Die Datei konnte nicht erzeugt werden, vielleicht ist \r\n" +
          "kein Speicherpßlatz mehr verfügbar oder es sind keine Rechte zum schreiben vorhanden. Fehler:\r\n" +
          ioe.getLocalizedMessage(),
          "Fehler", JOptionPane.ERROR_MESSAGE);
        ioe.printStackTrace();
      }
    }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton jButton1;
  private javax.swing.JButton jButton2;
  private javax.swing.JCheckBox jCheckBox1;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JPanel jPanel1;
  private javax.swing.JTextField jTextField1;
  private javax.swing.JTextField jTextField2;
  // End of variables declaration//GEN-END:variables

}
